package com.fau.wmbj.server.config;

import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.fau.wmbj.server.entity.Menu;
import com.fau.wmbj.server.entity.Role;
import com.fau.wmbj.server.entity.User;
import com.fau.wmbj.server.service.MenuService;
import com.fau.wmbj.server.service.RoleService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 权限
 *
 * @author jiawei
 * @version 1.0
 * @datetime 2024-02-26 17:55
 */
@Component
public class PermissionInterface implements StpInterface {

    @Resource
    private MenuService menuService;
    @Resource
    private RoleService roleService;

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        List<String> list = new ArrayList<>();
        // 2. 遍历角色列表，查询拥有的权限码
        for (String roleId : getRoleList(loginId, loginType)) {
            //查询角色和权限(这里根据业务自行查询)
            Role role = roleService.find(Long.valueOf(roleId));
            Set<Menu> menus = role.getMenus();
            List<String> collect = menus.stream().map(Menu::getName).collect(Collectors.toList());
            list.addAll(collect);
        }
        return list;
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        List<String> list = new ArrayList<>();
        User user = (User) StpUtil.getSession().get("user");
        String id = user.getRole().getId() + "";
        if (!CollectionUtil.contains(list, id)) {
            list.add(id);
        }

        return list;
    }
}
